﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using DataInfo;
using KenLib.BusinessManager;
using System.Web.UI.MobileControls;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public partial class Org_frmO_EmpWorkedCompInput : System.Web.UI.Page
{
    protected void Page_PreRender(object sender, EventArgs e)
    {
        ViewState["CountingSubmitOrg53"] = Session["CountingSubmitOrg53"];
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        
        ((Org_MasterPage)this.Master).changeTitle("職歴情報登録");
        ((Org_MasterPage)this.Master).HideLiArea("frmO_EmpWorkedCompInput");

        //Session["社員ID"] = "10";
        if (Session["社員ID"] == null || Session["社員ID"] == "" || Session["社員ID"].ToString() == "")
            Response.Redirect("frmO_EmpPhysicalExamInput.aspx");

        if (!Page.IsPostBack)
        {
            ViewState["IdCurrent_Org_53"] = "";
            ViewState["indexPage_Org_53"] = "0";
            ViewState["TempTableLoadOrg53"] = null;
            Session["CountingSubmitOrg53"] = Server.UrlEncode(System.DateTime.Now.ToString());
            //ClearTextPage();
            LoadDataGridView();
            LoadMessageError();

            string ngaysinh = new 基本情報Manager().getNgaySinh(Int32.Parse(Session["社員ID"].ToString()));
            if (ngaysinh.Length >= 10)
                hfNgaySinh.Value = ngaysinh.Substring(0, 10);
            else
                hfNgaySinh.Value = "";

        }

    }

    /// <summary>
    /// Load thong diep loi vao cac control valid
    /// </summary>
    private void LoadMessageError()
    {
        this.RequiredFieldValidator1.ErrorMessage = GetError("ER00001");
        this.RequiredFieldValidator2.ErrorMessage = GetError("ER00001");
        this.RequiredFieldValidator3.ErrorMessage = GetError("ER00001");
        this.RequiredFieldValidator4.ErrorMessage = GetError("ER00001");
        this.RequiredFieldValidator5.ErrorMessage = GetError("ER00001");
        this.RegularExpressionValidator1.ErrorMessage = GetError("ER00002");
        this.RegularExpressionValidator2.ErrorMessage = GetError("ER00002");
        CustomValidator1.ErrorMessage = GetError("ER00005");
        CustomValidator3.ErrorMessage = GetError("ER00005");
    }

    /// <summary>
    /// Coder: Ha Van Hoat
    /// Function: Lam sach lai text page
    /// </summary>
    private void ClearTextPage()
    {
        txt_会社名.Text = "";
        txt_開始年月日.Text = "";
        txt_仕事内容.Text = "";
        txt_主な実績.Text = "";
        txt_終了年月日.Text = "";
        txt_部門名.Text = "";
        txt_会社名.Focus();
    }

    protected void btn_戻る_Click(object sender, EventArgs e)
    {
        Response.Redirect("frmO_EmpAcademicInput.aspx");
    }

    protected void btn_次_Click(object sender, EventArgs e)
    {
        Response.Redirect("frmO_EmpImmiHistoryInput.aspx");
    }

    protected void btnリセット_Click(object sender, EventArgs e)
    {

        string strIndexCurrent = ViewState["IdCurrent_Org_53"] != null ? ViewState["IdCurrent_Org_53"].ToString() : "";
        if (strIndexCurrent != "")
        {
            DataTable dt = (DataTable)ViewState["Table_Org_53"]; ;
            int index = Int32.Parse(ViewState["index_Org_53"].ToString());

            string temp1 = dt.Rows[index]["会社名"].ToString();
            string temp2 = dt.Rows[index]["部門名"].ToString();
            string temp3 = dt.Rows[index]["仕事内容"].ToString();
            string temp4 = dt.Rows[index]["主な実績"].ToString();
            string temp5 = dt.Rows[index]["開始年月日"].ToString();
            string temp6 = dt.Rows[index]["終了年月日"].ToString();

            txt_会社名.Text = ConvertTexttoHTML(temp1);
            txt_部門名.Text = ConvertTexttoHTML(temp2);
            txt_仕事内容.Text = ConvertTexttoHTML(temp3);
            txt_主な実績.Text = ConvertTexttoHTML(temp4);
            txt_開始年月日.Text = temp5 != "" ? temp5.Substring(0, 10) : "";
            txt_終了年月日.Text = temp6 != "" ? temp6.Substring(0, 10) : "";
        }
        else
        {
            ClearTextPage();
            LoadDataGridView();
        }

    }

    protected void btn登録_Click(object sender, EventArgs e)
    {

        if (Session["CountingSubmitOrg53"].ToString() == ViewState["CountingSubmitOrg53"].ToString())
        {
            会社履歴情報 obj = new 会社履歴情報();

            obj.廃止区分 = 0;
            obj.会社名 = ConvertHTMLtoText(txt_会社名.Text.Trim().ToString());
            obj.部門名 = ConvertHTMLtoText(txt_部門名.Text.Trim().ToString());
            obj.仕事内容 = ConvertHTMLtoText(txt_仕事内容.Text.Trim().ToString());
            obj.主な実績 = ConvertHTMLtoText(txt_主な実績.Text.Trim().ToString());
            if (txt_開始年月日.Text != "")
            {
                //Boolean flag = checkDateValid(txt_開始年月日.Text);
                DateTime d1 = DateTime.Parse(txt_開始年月日.Text);
                obj.開始年月日 = d1;

            }

            if (txt_終了年月日.Text != "")
            {
                DateTime d2 = DateTime.Parse(txt_終了年月日.Text);
                obj.終了年月日 = d2;
            }

            obj.社員ID = Int32.Parse(Session["社員ID"].ToString());

            string strIdCurrent53 = ViewState["IdCurrent_Org_53"] != null ? ViewState["IdCurrent_Org_53"].ToString() : "";
            if (strIdCurrent53 == "")
            {

                bool check_exists = false;
                check_exists = new 会社履歴情報Manager().checkExistIn会社履歴情報InsertMode(obj);
                if (check_exists == true)
                {
                    // Had a duplicate. Not Valid
                    // show alert
                    string MessageCode = GetError("ER00009");
                    Page.ClientScript.RegisterStartupScript(typeof(Page), "Same 01", "alert('" + MessageCode + "');", true);
                }
                else
                {
                    int IdOuput;
                    int kq = new 会社履歴情報Manager().InsertPartialTable(obj, out IdOuput);
                    if (kq != 0 && IdOuput != 0)
                    {
                        ViewState["IdCurrent_Org_53_Output"] = IdOuput.ToString();
                        Session["CountingSubmitOrg53"] = Server.UrlEncode(System.DateTime.Now.ToString());
                        ClearTextPage();
                        LoadDataGridView();
                    }
                }
            }
            else
            {
                int intIdCurrent = Int32.Parse(ViewState["IdCurrent_Org_53"].ToString());
                obj.ID = intIdCurrent;
                
                bool checkHasChanged = false;
                checkHasChanged = new 会社履歴情報Manager().checkHasChangedIn会社履歴情報UpdateCurrent(obj);

                if (checkHasChanged == false)
                {
                    int kq = new 会社履歴情報Manager().UpdatePartialTable(obj, intIdCurrent);
                    if (kq != 0 && kq != -1)
                    {
                        btn登録.Text = "登録";
                        ClearTextPage();
                        LoadDataGridView();
                        ViewState["IdCurrent_Org_53"] = "";
                        ViewState["IdCurrent_Org_53_After"] = intIdCurrent.ToString();
                        Session["CountingSubmitOrg53"] = Server.UrlEncode(System.DateTime.Now.ToString());
                    }
                }
                else
                {
                    // check having a exists duplicate
                    bool check_exits = false;
                    check_exits = new 会社履歴情報Manager().checkExistIn会社履歴情報InsertMode(obj);
                    if (check_exits == true)
                    {
                        //Has a duplicate
                        // show alert
                        string MessageCode = GetError("ER00009");
                        Page.ClientScript.RegisterStartupScript(typeof(Page), "Same 01", "alert('" + MessageCode + "');", true);
                    }
                    else
                    {
                        int kq = new 会社履歴情報Manager().UpdatePartialTable(obj, intIdCurrent);
                        if (kq != 0 && kq != -1)
                        {
                            ClearTextPage();
                            LoadDataGridView();
                            btn登録.Text = "登録";
                            ViewState["IdCurrent_Org_53"] = "";
                            ViewState["IdCurrent_Org_53_After"] = intIdCurrent.ToString();
                            Session["CountingSubmitOrg53"] = Server.UrlEncode(System.DateTime.Now.ToString());
                        }
                    }
                }
            }
        }
        else
        {
            ClearTextPage();
            LoadDataGridView();
        }
    }

    /// <summary>
    /// Alert thong diep loi
    /// </summary>
    private void ErrorInput()
    {
        String strScr;
        strScr = "<script type='text/javascript'>";
        strScr += "alert('" + GetError("ER00001") + "')";
        strScr += "</script>";
        ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "a", strScr, false);
    }

    /// <summary>
    /// Alert thong diep loi
    /// </summary>
    /// <param name="str"></param>
    private void ErrorValide(String str)
    {
        String strScr;
        strScr = "<script type='text/javascript'>";
        strScr += "alert('" + GetError(str) + "')";
        strScr += "</script>";
        ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "a", strScr, false);
    }

    /// <summary>
    /// Load du lieu cho gridview
    /// </summary>
    private void LoadDataGridView()
    {
        //DataTable lst = new 会社履歴情報Manager().SelectPartial(Session["社員ID"].ToString());
        DataTable lst = new 会社履歴情報Manager().SelectPartialOrg53(Session["社員ID"].ToString());
        if (lst.Rows.Count > 0)
        {
            grv_human.DataSource = lst;
            ViewState["TempTableLoadOrg53"] = lst;
            grv_human.DataBind();
        }
        else
        {
            string Header = "ID,会社名,部門名,開始年月日,終了年月日";
            ShowGridViewNotClassEmpty(grv_human, Header, "データーがありません。");
        }
    }

    protected void grv_human_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grv_human.PageIndex = e.NewPageIndex;
        ViewState["indexPage_Org_53"] = e.NewPageIndex.ToString();
        LoadDataGridView();
    }

    /// <summary>
    /// Coder: Ha Van Hoat
    /// Function: Lay thong diep loi ung voi ma loi
    /// </summary>
    public String GetError(string errorid)
    {
        Error er = new Error();
        er.ErrorID = errorid;
        ErrorManager frm_error = new ErrorManager();
        DataTable dt = frm_error.getError(er);
        return dt.Rows[0][2].ToString();
    }

    /// <summary>
    /// Coder: Ha Van Hoat
    /// Function: Kiem tra dinh dang ngay thang co hop le ko
    /// </summary>
    protected Boolean checkDateValid(String input)
    {
        String pattern = @"^(?ni:(?=\d)((?'year'((1[6-9])|([2-9]\d))\d\d)(?'sep'[/.-])(?'month'0?[1-9]|1[012])\2(?'day'((?<!(\2((0?[2469])|11)\2))31)|(?<!\2(0?2)\2)(29|30)|((?<=((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(16|[2468][048]|[3579][26])00)\2\3\2)29)|((0?[1-9])|(1\d)|(2[0-8])))(?:(?=\x20\d)\x20|$))?((?<time>((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2}))?)$";
        return Regex.IsMatch(input, pattern);
    }

    /// <summary>
    /// Coder: Ha Van Hoat
    /// Function: Chuyen chuoi sang ma HTML
    /// </summary>
    public string ConvertTexttoHTML(string temp)
    {
        temp = temp.Replace("<", "&lt;");
        temp = temp.Replace(">", "&gt;");
        return temp;
    }

    /// <summary>
    /// Coder: Ha Van Hoat
    /// Function: Chuyen tu ma HTML sang chuoi
    /// </summary>
    public string ConvertHTMLtoText(string temp)
    {
        temp = temp.Replace("&lt;", "<");
        temp = temp.Replace("&gt;", ">");
        temp = temp.Replace(Convert.ToString((char)13), "<br/>");
        return temp;
    }

    /// <summary>
    /// Coder: Ha Van Hoat
    /// Function: Xu ly hien thi chuoi dai len GridView
    /// </summary>
    public string ShowTextLength(object str)
    {
        if (str == null || str.ToString() == "")
            return "";
        string temp = str.ToString();
        if (checkContainsUnicodeCharacter(temp))
        {
            //true tieng nhat
            if (temp.Length > 10)
            {
                temp = temp.Substring(0, 10) + "...";
            }
        }
        else
        {
            //tieng viet
            if (temp.Length > 20)
            {
                temp = temp.Substring(0, 20) + "...";
            }
        }

        return temp;
    }

    /// <summary>
    /// Coder: Ha Van Hoat
    /// Function: Kiem tra chuoi dau vao co thuoc bang ma Unicode
    /// </summary>
    public bool checkContainsUnicodeCharacter(string input)
    {
        const int MaxAnsiCode = 255;
        char[] a = input.ToCharArray();
        for (int i = 0; i < a.Length; i++)
        {
            if (a[i] > MaxAnsiCode)
            {
                return true;
            }
        }
        return false;
    }

    protected void grv_human_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='none';";
            e.Row.Attributes.Add("onclick", "javascript:__doPostBack('ctl00$ContentPlaceHolder1$grv_human','Load$" + e.Row.RowIndex + "')");
        }
    }

    protected void grv_human_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Load"))
        {
            //ErrorValide("ER00001");
            int pagecurrent = Int32.Parse(ViewState["indexPage_Org_53"].ToString());
            int index;
            if (pagecurrent == 0)
                index = Int32.Parse(e.CommandArgument.ToString());
            else
                index = Convert.ToInt32(e.CommandArgument) + pagecurrent * 10;
            if (index == -1) return;


            DataTable dt ;
            //dt = new 会社履歴情報Manager().SelectPartial(Session["社員ID"].ToString());
            dt = (DataTable)ViewState["TempTableLoadOrg53"];
            if (dt!=null && dt.Rows.Count > 0)
            {
                string temp1 = dt.Rows[index]["会社名"].ToString();
                string temp2 = dt.Rows[index]["部門名"].ToString();
                string temp3 = dt.Rows[index]["仕事内容"].ToString();
                string temp4 = dt.Rows[index]["主な実績"].ToString();
                string temp5 = dt.Rows[index]["開始年月日"].ToString();
                string temp6 = dt.Rows[index]["終了年月日"].ToString();

                txt_会社名.Text = ConvertTexttoHTML(temp1);
                txt_部門名.Text = ConvertTexttoHTML(temp2);
                txt_仕事内容.Text = ConvertTexttoHTML(temp3);
                txt_主な実績.Text = ConvertTexttoHTML(temp4);
                txt_開始年月日.Text = temp5 != "" ? temp5.Substring(0, 10) : "";
                txt_終了年月日.Text = temp6 != "" ? temp6.Substring(0, 10) : "";

                ViewState["IdCurrent_Org_53"] = dt.Rows[index]["ID"].ToString();
                btn登録.Text = "更新";
                ViewState["Table_Org_53"] = dt;
                ViewState["index_Org_53"] = index.ToString();
            }
            else
            {
                string Header = "ID,会社名,部門名,開始年月日,終了年月日";
                ShowGridViewNotClassEmpty(grv_human, Header, "データーがありません。");
            }
        }
    }
    
    protected void grv_human_PreRender(object sender, EventArgs e)
    {

        //Mode Update cua Insert
        if (ViewState["IdCurrent_Org_53_After"] != null && ViewState["IdCurrent_Org_53_After"] != "")
        {
            if (string.IsNullOrEmpty(ViewState["IdCurrent_Org_53_After"].ToString()))
                return;
            for (int i = 0; i < grv_human.Rows.Count; i++)
            {
                string IdKey = grv_human.DataKeys[i].Value.ToString();
                string IdCurrent = ViewState["IdCurrent_Org_53_After"].ToString();
                if (IdKey == IdCurrent)
                {
                    grv_human.Rows[i].CssClass = "update";
                    ViewState["IdCurrent_Org_53_After"]="";
                    break;
                }
            }
        }

        //Mode insert

        if (ViewState["IdCurrent_Org_53_Output"] != null && ViewState["IdCurrent_Org_53_Output"] != "")
        {
            if (string.IsNullOrEmpty(ViewState["IdCurrent_Org_53_Output"].ToString()))
            {
                return;
            }

            for (int i = 0; i < grv_human.Rows.Count; i++)
            {
                string IdKey = grv_human.DataKeys[i].Value.ToString();
                string IdCurrent = ViewState["IdCurrent_Org_53_Output"].ToString();

                if (IdKey == IdCurrent)
                {
                    grv_human.Rows[i].CssClass = "insert";
                    ViewState["IdCurrent_Org_53_Output"] = "";
                    break;
                }
            }
        }

    }
    /// <summary>
    /// Hien thi du lieu rong cho Gridview
    /// </summary>
    /// <param name="grv"></param>
    /// <param name="strTableHeader"></param>
    /// <param name="strEmpty"></param>
    public void ShowGridViewNotClassEmpty(GridView grv, string strTableHeader, string strEmpty)
    {
        DataTable dt = new DataTable();
        string[] arrColumnNames = strTableHeader.Split(',');
        foreach (string str in arrColumnNames)
        {
            dt.Columns.Add(str);
        }
        grv.ShowFooter = false;
        DataRow r = dt.NewRow();
        dt.Rows.InsertAt(r, 0);
        grv.DataSource = dt;
        grv.DataBind();
        grv.Rows[0].Cells.Clear();
        TableCell cell = new TableCell();
        cell.ColumnSpan = grv.Columns.Count + 1;
        cell.Text = strEmpty;
        grv.Rows[0].Cells.Add(cell);

    }

}
